package com.bsoft.server.processor;

import com.bsoft.server.annotation.RpcService;
import com.bsoft.server.cache.RpcServiceCache;
import com.bsoft.server.config.RpcServerProperties;
import com.bsoft.server.transport.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.CommandLineRunner;

@Slf4j
public class RpcServerProcessor implements BeanPostProcessor , CommandLineRunner {

    @Autowired
    NettyServer server;
    @Autowired
    RpcServerProperties properties;

    /**
     * bean实例化之后，对开放的bean进行缓存（遍历@RpcService注解）
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        RpcService rpcService = bean.getClass().getAnnotation(RpcService.class);
        if (rpcService != null) {
            // 放入缓存，以供调用
            RpcServiceCache.putService(rpcService.interfaceType().getName(), bean);
        }
        return bean;
    }

    @Override
    public void run(String... args) throws Exception {
        new Thread(()->{
            server.start(properties.getPort());
        }).start();
    }
}
